package com.qiandw.security.entity;

import com.qiandw.entity.security.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.security.authentication.jaas.JaasGrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.security.Principal;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @author coxx
 */

public class UserDetailImpl extends User implements UserDetails, Principal {

    public UserDetailImpl(User user){
        setId(user.getId());
        setEducation(user.getEducation());
        setIdNo(user.getIdNo());
        setMail(user.getMail());
        setMobile(user.getMobile());
        setPassword(user.getPassword());
        setUsername(user.getUsername());
        setRoles(user.getRoles());
        setIsEnabled(user.getIsEnabled());
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getRoles().stream().map(role -> new JaasGrantedAuthority("ROLE_"+ role.getName(),this)).collect(Collectors.toList());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return getIsEnabled();
    }

    @Override
    public String toString() {
       return super.toString();
    }

    @Override
    public int hashCode() {
        return this.getId().hashCode();
    }

    @Override
    public String getName() {
        return this.getUsername();
    }
}
